import { login, userInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTimeout, removeTimeout } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
import Router from '@/router/index'
const state = {
  token: getToken('token') || '',
  userinfo: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  setuserinfo(state, data) {
    state.userinfo = { ...data }
  },
  removetoken(state) {
    state.token = ''
  },
  removeuserinfo(state) {
    state.userinfo = {}
  }
}
const actions = {
  async login(state, data) {
    const res = await login(data)
    state.commit('setToken', res.data)
  },
  async getuserinfo(state) {
    const res = await userInfo()
    const detail = await getUserDetailById(res.data.userId)
    state.commit('setuserinfo', { ...res.data, ...detail.data })
    const timeout = Date.now()
    setTimeout(timeout)
  },
  logout(state) {
    state.commit('removetoken')
    state.commit('removeuserinfo')
    removeToken()
    removeTimeout()
    Router.options.routes = [...constantRoutes, { path: '*', redirect: '/404', hidden: true }]
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
